package com.xzq.daoimpl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.xzq.dao.OrdersDao;
import com.xzq.entity.Orders;
import com.xzq.entity.Page;
import com.xzq.entity.User;
import com.xzq.entity.page.PageSize;
import com.xzq.util.HibernatePage;
@Repository
public class OrdersDaoImpl extends HibernatePage<Orders> implements OrdersDao{

	@Override
	public Page findAllOrders(Page page) {
		// TODO 自动生成的方法存根
		return null;
	}

	@Override
	public Page findOneUserAllOrders(Page page,User user) {
		String hql = "from Orders o where o.user.id=? and o.flag=1";
		Object[] obj = {user.getId()};
		page = findHibernatePage(page, hql, obj, PageSize.ordersSize);
		return page;
	}

	@Override
	public Orders findOneOrder(Orders orders) {
		orders = template.get(Orders.class, orders.getId());
		return orders;
	}

	@Override
	public int addOrders(Orders orders) {
		Serializable s = template.save(orders);
		int count = (Integer) s;
		return count;
	}

	@Override
	public int modifyOrders(Orders orders) {
		try {
			template.update(orders);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public int deleteOrders(Orders orders) {
		try {
			template.delete(orders);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public Double findOneOrdersSumPrice(Orders orders) {
		final String sql = "SELECT SUM(onp.price*onp.num) FROM orders o LEFT JOIN orderandproduct onp ON (o.id=onp.orders_id) WHERE o.id = ?";
		final int id = orders.getId();
		List<Double> list = new ArrayList<Double>();
		list = template.execute(new HibernateCallback<List<Double>>() {

			@Override
			public List<Double> doInHibernate(Session session)
					throws HibernateException {
				Query q = session.createSQLQuery(sql);
				q.setParameter(0, id);
				List<Double> list = q.list();
				return list;
			}
		});
		Double sumPrice = 0.0;
		if(list.size()>0){
			sumPrice = list.get(0);
		}
		return sumPrice;
	}

	@Override
	public Orders findOneOrdersWhereItIsAShopCat(User user) {
		Orders o = null;
		String hql = "from Orders o where o.user.id=? and o.flag=0";
		Object[] obj = {user.getId()};
		List<Orders> list = new ArrayList<Orders>();
		list = (List<Orders>) template.find(hql, obj);
		if(list.size()>0){
			o = list.get(0);
		}
		return o;
	}

}
